package main

import (
	"encoding/json"
	"fmt"
)

//结构体字段不大写，不能被json包导出,序列化结果不包含不能导出的字段
type teacher struct {
	Name   string  // `json:"name"`
	Age    int     `json:"age"`
	Beauty float64 `json:"beauty"`
}

func main() {
	//序列化结构体
	teacher1 := teacher{"bdy", 28, 9.2}
	bdy, err := json.Marshal(teacher1)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("teacher1=%s\n", bdy)
	//反序列化到结构体
	var teacher1_unmarshal teacher
	err = json.Unmarshal(bdy, &teacher1_unmarshal)
	if err != nil {
		fmt.Printf("Unmarshal1:err=%v", err)
	}
	fmt.Printf("teacher1_unmarshal=%v\n\n", teacher1_unmarshal)

	//序列化map，map-key小些依然可以导出
	teacher2 := map[string]interface{}{
		"name":      "xzay",
		"age":       18,
		"introduce": map[string]float64{"beauty": 9.0, "skill": 9.5},
	}
	xzay, err := json.Marshal(teacher2)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("teacher2=%s\n", xzay)
	//反序列化到map
	var teacher2_unmarshal map[string]interface{}
	err = json.Unmarshal(xzay, &teacher2_unmarshal)
	if err != nil {
		fmt.Printf("Unmarshal2:err=%v", err)
	}
	fmt.Printf("teacher2_unmarshal=%v\n\n", teacher2_unmarshal)

	//序列化切片
	teachers := []interface{}{&teacher1, teacher2}
	ts, err := json.Marshal(teachers)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("teacher3=%s\n", ts)
	//反序列化到切片
	var teacher3_unmarshal []interface{}
	err = json.Unmarshal(ts, &teacher3_unmarshal)
	if err != nil {
		fmt.Printf("Unmarshal3:err=%v", err)
	}
	fmt.Printf("teacher3_unmarshal=%v\n\n", teacher3_unmarshal)
	fmt.Println(teacher2_unmarshal["name"])

}
